package lruchche;

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache extends LinkedHashMap<Integer,Integer>{
    public int capacity;
    public LRUCache(int capacity) {
        //这里的true 代表基于 访问顺序
        super(capacity,0.75F,true);
        this.capacity = capacity;
    }

    @Override
    public Integer get(Object key) {
        return super.getOrDefault(key,-1);
    }

    @Override
    public Integer put(Integer key, Integer value) {
        return super.put(key, value);
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
        return size() > capacity;
    }

    public static void main(String[] args) {
        LRUCache lruCache = new LRUCache(3);
        lruCache.put(123,1);
        lruCache.put(110,1);
        lruCache.put(132,1);
        System.out.println(lruCache);
        System.out.println("===========");
        System.out.println(lruCache.get(123));
        System.out.println(lruCache);

        System.out.println("存放元素:将最久未使用的元素进行替换");
        lruCache.put(999,99);

        System.out.println(lruCache);
    }
    public static void main2(String[] args) {
        LinkedHashMap<String,Integer> linkedHashMap = new LinkedHashMap<>(16,0.7f,true);
        linkedHashMap.put("神域",1);
        linkedHashMap.put("深鱼",1);
        linkedHashMap.put("hello",1);
        System.out.println(linkedHashMap);
        System.out.println("===========");
        System.out.println(linkedHashMap.get("深鱼"));
        System.out.println(linkedHashMap);
    }
}
